#include <iostream>
#include <string>

#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>

const std::string gpath = "/home/wk/linux";
const int gpro_id = 0100;
const int gsize = 4096;

static key_t GetKey()
{
    return ftok(gpath.c_str(), gpro_id);
}

class ShareMemory
{
public:
    ShareMemory()
        : _shmid(0), _key(-1)
    {
    }

    ~ShareMemory()
    {
    }

    void Create()
    {
        _key = GetKey();
        _shmid = shmget(_key, gsize, IPC_CREAT | IPC_EXCL | 0600);
    }

    void Get()
    {
        _key = GetKey();
        _shmid = shmget(_key, gsize, IPC_CREAT);
    }

    void Attach()
    {
        _addr = shmat(_shmid, nullptr, 0);
    }

    void DeAttch()
    {
        shmdt(_addr);
    }

    void *GetAddr()
    {
        return _addr;
    }

    void Destroy()
    {
        shmctl(_shmid, IPC_RMID, nullptr);
    }

private:
    int _shmid;
    key_t _key;
    void *_addr;
};

ShareMemory shm;